package org.projecteboot.reptile.common.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.projecteboot.compent.core.utils.MapUtil;
import org.projecteboot.compent.core.utils.UrlUtil;
import org.projecteboot.reptile.common.constant.CommonConst;
import org.projecteboot.reptile.common.entity.ReptilePage;
import org.projecteboot.reptile.common.mapper.ExtReptilePageMapper;
import org.projecteboot.reptile.common.mapper.ReptilePageMapper;
import org.projecteboot.reptile.common.service.ReptilePageService;
import org.springframework.stereotype.Service;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 爬虫页面 服务实现类
 * </p>
 *
 * @author LuoQiang
 * @since 2019-08-30
 */
@Service
@Slf4j
public class ReptilePageServiceImpl extends ServiceImpl<ReptilePageMapper, ReptilePage> implements ReptilePageService {
    @Resource
    private ExtReptilePageMapper extReptilePageMapper;


    @Override
    public ReptilePage findByPage(Page page) {
        Request request = page.getRequest();
        String reqUrl = request.getUrl();
        Map<String, Object> extras = request.getExtras();

        Matcher matcher = Pattern.compile(CommonConst.URL_REG_PATTERN).matcher(reqUrl);
        if (!matcher.matches()) {
            log.info("页面:{}不是url，无法解析", reqUrl);
            return null;
        }
        String url = matcher.group(3);
        Long pageRuleId = MapUtil.getMapValue(extras, CommonConst.PAGEPROCESSOR_PAGE_RULE_ID);
        if (pageRuleId == null) {
            log.info("页面:{}，没有查询到pageRuleId");
        }
        return findByUrlAndPageRuleId(url, pageRuleId);
    }

    @Override
    public ReptilePage findByUrlAndPageRuleId(String url, Long pageRuleId) {
        String urlHash = UrlUtil.urlHash(url);
        List<ReptilePage> reptilePages = extReptilePageMapper.listByUrlHashAndPageRuleIdAndUrl(urlHash, pageRuleId, url);
        if (CollectionUtils.isEmpty(reptilePages)) {
            return null;
        }
        ReptilePage reptilePage = reptilePages.get(0);
        return reptilePage;
    }

    @Override
    public List<ReptilePage> listBySuccess(String success) {
        return extReptilePageMapper.listBySucess(success);
    }
}
